package tw.com.hitevision.whiteboard.android.youtube.searchView;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.recyclerview.widget.DiffUtil;
import androidx.recyclerview.widget.ListAdapter;
import androidx.recyclerview.widget.RecyclerView;

import java.util.List;

import tw.com.hitevision.whiteboard.android.R;


public class YoutubeSuggestionAdapter extends ListAdapter<String, RecyclerView.ViewHolder> {

    private final String TAG = this.getClass().getSimpleName();
    private final Listener listener;
    private final List<String> suggestionList;

    private static final DiffUtil.ItemCallback<String> diffCallback = new DiffUtil.ItemCallback<String>() {
        @Override
        public boolean areItemsTheSame(@NonNull String oldItem, @NonNull String newItem) {
            return oldItem.equals(newItem);
        }

        @Override
        public boolean areContentsTheSame(@NonNull String oldItem, @NonNull String newItem) {
            return oldItem.equals(newItem);
        }

        @Override
        public Object getChangePayload(@NonNull String oldItem, @NonNull String newItem) {
            return oldItem.equals(newItem);
        }
    };

    public YoutubeSuggestionAdapter(List<String> suggestionList, Listener listener) {
        super(diffCallback);
        this.listener = listener;
        this.suggestionList = suggestionList;
    }

    static class ViewHolder extends RecyclerView.ViewHolder {

        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            layout = itemView.findViewById(R.id.youtube_player_suggestion_recycler_view_layout);
            suggestion = itemView.findViewById(R.id.youtube_search_suggestion_recycler_view_suggestion);
        }

        private final ConstraintLayout layout;
        private final TextView suggestion;
    }

    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        LayoutInflater inflater = LayoutInflater.from(parent.getContext());
        return new ViewHolder(inflater.inflate(R.layout.menu_youtube_search_suggestion_recycler_view_item, parent, false));
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
        ((ViewHolder)holder).suggestion.setText(suggestionList.get(position));
        ((ViewHolder)holder).layout.setOnClickListener(v -> listener.ItemOnClick(suggestionList.get(position)));
    }

    @Override
    public void submitList(@Nullable List<String> list) {
        super.submitList(list);
    }

    @Override
    public int getItemCount() {
        return suggestionList.size();
    }

    interface Listener {
        void ItemOnClick(String suggestion);
    }
}
